﻿#region Usings

using System;
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

#endregion

namespace xConnected.Helpers
{
    public class JsonNetResult : JsonResult
    {
        public JsonSerializerSettings SerializerSettings { get; set; }

        public JsonNetResult()
        {
            // create serializer settings
            SerializerSettings = new JsonSerializerSettings();
            // setup default serializer settings
            SerializerSettings.Converters.Add(new IsoDateTimeConverter());
        }

        public override void ExecuteResult(ControllerContext context)
        {
            // verify we have a contrex
            if (context == null)
                throw new ArgumentNullException("context");

            // get the current http context response
            var response = context.HttpContext.Response;
            // set content type of response
            response.ContentType = !String.IsNullOrEmpty(ContentType) ? ContentType : "application/json";
            // set content encoding of response
            if (ContentEncoding != null)
                response.ContentEncoding = ContentEncoding;

            // verify this response has data
            if (Data == null)
                return;

            // serialize the object to JSON using JSON.Net
            var jsonText = JsonConvert.SerializeObject(Data, Formatting.Indented, SerializerSettings);
            // write the response
            response.Write(jsonText);
        }
    }
}